#!/usr/bin/env bash

# PHAN_TEST_PARALLEL can be set to 0 in your .bashrc (or other shell configuration) if you do not want to test in parallel by default.
PHAN_TEST_PARALLEL=${PHAN_TEST_PARALLEL:-1}
if [[ "$#" != 0 ]]; then
	if [[ "$#" == 1 && "$@" == "--parallel" ]]; then
		if type parallel >/dev/null; then
			PHAN_TEST_PARALLEL=1
		else
			echo "GNU parallel is not installed, running tests in sequence"
		fi
	else
		echo "Usage: $0 [--parallel]" 1>&2
		echo "Runs all unit tests, integration tests, and test scripts" 1>&2
		exit 1
	fi
fi

# NOTE: We run these in a single phpunit run. The output is easier to read
#TEST_SUITES="PhanTest"
#TEST_SUITES+=" UtilTest"
#TEST_SUITES+=" SoapTest"
#TEST_SUITES+=" RasmusTest"
#TEST_SUITES+=" LanguageTest"

TEST_SUITES="__FakeAllPHPUnitTests"
TEST_SUITES+=" __FakeSelfTest"
TEST_SUITES+=" __FakeSelfFallbackTest"
TEST_SUITES+=" __FakeRewritingTest"
TEST_SUITES+=" __FakePluginTest"
TEST_SUITES+=" __FakeRealTypesTest"
TEST_SUITES+=" __FakeFallbackTest"
TEST_SUITES+=" __FakeToolTest"
TEST_SUITES+=" __FakeConfigOverrideTest"
TEST_SUITES+=" __FakeFixerTest"
TEST_SUITES+=" __FakePhantasmTest"
if type sqlite3 >/dev/null 2>/dev/null; then
    TEST_SUITES+=" __FakePhoundTest"
fi
TEST_SUITES+=" __FakeInferMissingTypesTest"
TEST_SUITES+=" __FakeOverrideReturnTypesTest"
TEST_SUITES+=" __FakeEmptyMethodsPluginTest"

FAILURES=""

# Suppress this notice when running tests to save screen space
export PHAN_SUPPRESS_PHP_UPGRADE_NOTICE=1

if [[ "$PHAN_TEST_PARALLEL" == 1 ]]; then
	# Note: Must install GNU parallel for this to work.
	if ! echo "$TEST_SUITES" | tr ' ' '\n' | parallel --jobs 4 --no-notice --joblog tests/.run_all_tests.joblog --arg-sep ' ' tests/run_test --print-test-suite; then
		FAILURES=" $(awk '$7 >= 1 && $11 { print $11}' < tests/.run_all_tests.joblog | tr '\n' ' ')"
	fi
else
	for TEST_SUITE in $TEST_SUITES; do
		if ! tests/run_test --print-test-suite "$TEST_SUITE"; then
			FAILURES="$FAILURES $TEST_SUITE"
		fi
		echo
	done
fi
if [[ "x$FAILURES" != "x" ]]; then
	echo "These tests or checks failed (see above output): $FAILURES"
	exit 1
else
	echo 'All tests and checks passed!'
fi
